﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
using System.IO;
using CDO;
using ADODB;
using System.Reflection;
using Common.Logging;

namespace DotNetNexusSpam
{
    class CDOUtil
    {
        private static ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        
        /// <summary>
        /// The file containing the email is converted into a CDO.Message object. 
        /// Once you have the message object configured, reading, modifying the message and it's associated attachments
        /// becomes quite simple.
        /// I tried to avoid using COM objects but could not find any native alternative C# class with similar funcionality. 
        /// I thought MailMessage was a wrapper for the CDO class but it doesn't contain any method to load itseld from a file/stream.
        /// </summary>
        /// <param name="emailPath">Path to the file containing the email inside the file system.</param>
        public static CDOMessageWrapper ConvertEmailToCDO(string emailPath)
        {
            Message cdoMessage = new Message();
            CDOMessageWrapper messageWrapper = null;
            try
            {
                ADODB.Stream st = new ADODB.Stream();
                st.Charset = "ascii";
                st.Open(Missing.Value, ConnectModeEnum.adModeUnknown, StreamOpenOptionsEnum.adOpenStreamUnspecified, "", "");
                st.LoadFromFile(emailPath);

                IDataSource iDataSource = cdoMessage.DataSource;
                iDataSource.OpenObject(st, "_Stream");
                st.Close();
                messageWrapper = new CDOMessageWrapper(cdoMessage, emailPath);
            }
            catch (Exception exp) {
                _log.Error(String.Format("Email could not be converted: {0}", exp));
                cdoMessage = null; 
            }
            return messageWrapper;
        }

        /// <summary>
        /// A tag is added to the subject of the suspicious emails and the resulting email
        /// is saved to the original location.
        /// If your are debugging locally and are using the Mail Enable directory, remember 
        /// your program will need administrative rights in order to update or delete files from this directory.
        /// </summary>
        /// <param name="email">Object containing email's information</param>
        /// <param name="emailPath">Path to email file</param>
        /// <param name="tagForSubject">Tag to add to email's subject</param>
        /// <returns></returns>
        public static bool TagSubject(CDOMessageWrapper email, string emailPath, string tagForSubject)
        {
            bool isSuccess = false;
            email.CDOMessage.Subject = tagForSubject + email.CDOMessage.Subject;
            try
            {
                ADODB.Stream st = new ADODB.Stream();
                st.Charset = "ascii";
                st.Open(Missing.Value, ConnectModeEnum.adModeUnknown, StreamOpenOptionsEnum.adOpenStreamUnspecified, "", "");
                st.Type = StreamTypeEnum.adTypeText;
                st.LoadFromFile(emailPath);

                IDataSource iDataSource = email.CDOMessage.DataSource;
                iDataSource.SaveToObject(st, "_Stream");

                st.SaveToFile(emailPath, SaveOptionsEnum.adSaveCreateOverWrite);
                st.Close();
            }
            catch (Exception exp)
            {
                _log.Error(String.Format("Email's subject could not be updated {0}", exp));   
            }
            return isSuccess;
        }
    }
}
